from django_redis import get_redis_connection
from rest_framework import serializers


class ImageCodeCheckSerializer(serializers.Serializer):
    img_id=serializers.UUIDField()
    text=serializers.CharField(max_length=4,min_length=4)
    def validate(self, attrs):
        img_id=attrs['img_id']
        text=attrs['text']
        redis_conn=get_redis_connection('verify_codes')
        real_img_code_text=redis_conn.get("img_%s"%img_id)
        if not real_img_code_text:
            raise serializers.ValidationError('无效的图片验证码')
        redis_conn.delete("img_%s" % img_id)
        real_img_code_text=real_img_code_text.decode()
        if real_img_code_text.lower()!=text.lower():
            raise serializers.ValidationError('图片验证码错误')
        mobile=self.context['view'].kwargs['mobile']
        send_flag=redis_conn.get(mobile)
        if send_flag:
            raise serializers.ValidationError('发送短信次数过于频繁')
        return attrs
